#include "hudvideoeffect.h"
#include "effectcontainermanager.h"
#include <osgViewer\View>
#include "datatypedefine.h"
#include "datamanager.h"
#include "utility.h"

namespace VrDataCore
{
	HudVideoEffect::HudVideoEffect():_ve(NULL)
	{
		_videoUpdateCallback = new VideoUpdateCallback(this);
	}

	HudVideoEffect::~HudVideoEffect()
	{}

	void HudVideoEffect::buildPropertyMap()
	{}

	void HudVideoEffect::apply(CoreBase::ActorBase* actor)
	{
		if(!isIdle())
			return;
		osgViewer::View* v = EffectContainerManager::GetInstance().getMainView();
		int w = v->getCamera()->getViewport()->width();
		int h = v->getCamera()->getViewport()->height();
		if(!_ve.valid())
		{
			_ve = new VideoEffect;
			_ve->init();
		}
		QString vf = DataManager::GetInstance().getApplicationDir() + CONTEXT_DIR + SCENE_VIDEO + "\\"+_videofile;
		_ve->loadVideo(ChineseTexttoStdstring(vf));
		bool flip = _ve->isFlip();
		dynamic_cast<CoreBase::PlaneShape*>(_drawable.get())->reset(
			osg::Vec3(0,0,0),osg::Vec3(w,0,0),osg::Vec3(w,h,0),osg::Vec3(0,h,0),
			flip?osg::Vec2(0,_ve->getVideoHeight()):osg::Vec2(0,0),
			flip?osg::Vec2(_ve->getVideoWidth(),_ve->getVideoHeight()):osg::Vec2(_ve->getVideoWidth(),0),
			flip?osg::Vec2(_ve->getVideoWidth(),0):osg::Vec2(_ve->getVideoWidth(),_ve->getVideoHeight()),
			flip?osg::Vec2(0,0):osg::Vec2(0,_ve->getVideoHeight()));
		_videoLength = _ve->getVideoLength()*1000;
		_startT = osg::Timer::instance()->tick();
		EffectContainerManager::GetInstance().getRootDrawable()->getOSGNode()->addUpdateCallback(_videoUpdateCallback);
		EffectContainerManager::GetInstance().addEffectHudNode(_drawable->getOSGNode());
		_ve->apply(this);
		EffectBase::apply(actor);
	}

	void HudVideoEffect::unApply(CoreBase::ActorBase* actor)
	{
		if(isIdle())
			return;
		EffectContainerManager::GetInstance().getRootDrawable()->getOSGNode()->removeUpdateCallback(_videoUpdateCallback);
		EffectContainerManager::GetInstance().removeEffectHudNode(_drawable->getOSGNode());
		_ve->unApply(this);
		EffectBase::unApply(actor);
	}

	void HudVideoEffect::createDrawable()
	{
		_drawable = new CoreBase::PlaneShape;
	}

	void HudVideoEffect::setVideoFileName(QString f)
	{
		_videofile = f;
	}

	QString HudVideoEffect::getVideoFileName()
	{
		return _videofile;
	}

	void HudVideoEffect::callback()
	{
		if(isIdle())
			return;
		osg::Timer_t nowtime = osg::Timer::instance()->delta_m(_startT,osg::Timer::instance()->tick());
		if(nowtime>_videoLength)
		{
			unApply(this);
		}
	}
}